import numpy as np
from abc import ABC, abstractmethod


class AudioProcessor(ABC):
    """音频处理器的基类"""

    def __init__(self, parameters):
        self.parameters = parameters
        self.sample_rate = 44100
        self.buffer_size = 512
        self.is_active = False
        self.input_channels = 2  # 默认假设立体声

    @abstractmethod
    def process(self, audio_data: np.ndarray) -> np.ndarray:
        """处理音频数据，返回处理后的数据"""
        pass

    def update_parameters(self, new_parameters):
        """更新处理器参数"""
        self.parameters.update(new_parameters)

    def set_sample_rate(self, sample_rate: int):
        """设置采样率"""
        self.sample_rate = sample_rate

    def set_buffer_size(self, buffer_size: int):
        """设置缓冲区大小"""
        self.buffer_size = buffer_size

    def set_input_channels(self, channels: int):
        """设置输入通道数"""
        self.input_channels = channels

    def _ensure_correct_shape(self, audio_data: np.ndarray) -> np.ndarray:
        """确保音频数据具有正确的形状"""
        if audio_data.ndim == 1:
            # 一维数组，转换为二维 (samples, 1)
            return audio_data.reshape(-1, 1)
        elif audio_data.ndim == 2 and audio_data.shape[1] != self.input_channels:
            # 通道数不匹配，可能需要转换
            if audio_data.shape[1] == 1 and self.input_channels == 2:
                # 单声道转立体声：复制通道
                return np.repeat(audio_data, self.input_channels, axis=1)
            elif audio_data.shape[1] == 2 and self.input_channels == 1:
                # 立体声转单声道：取平均值
                return np.mean(audio_data, axis=1, keepdims=True)
        return audio_data

    def start(self):
        """启动处理器"""
        self.is_active = True

    def stop(self):
        """停止处理器"""
        self.is_active = False

    def reset(self):
        """重置处理器状态"""
        self.is_active = False